
/**
 *  1. Promis就是一个类，在执行这个类的时候需要传递一个执行器进去，执行器立即执行
 *  2. Promise中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
 *      pending -> fulfilled
 *      pending -> rejected
 *      一旦状态确定就不可更改
 *
 *  3. resolve 和reject函数是用来改变状态的
 *      resolve: fulfilled
 *      reject: rejected
 *  4. then 方法内部做的事情就是判断状态， 如果状态是成功调用成功的回调函数，如果状态是失败就调用失败
 *      的回调函数，then方法是被定义在原型对象中的
 *  5.  then成功回调有一个参数，表示成功之后的值，then失败回调有一个参数，表示失败后的原因
 *  6.  同一个Pormise对象下面的hten方法是可以被多次调用的
 *  7.  then方法是可以被链式调用的，then的返回值是一个promise对象，后面then方法的回调函数拿到的值是上
 *      一个then 方法的回调函数的返回值
 */


const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {

    constructor(executor) {
        try {
            executor(this.resolve, this.reject);

        } catch (e) {
            this.reject(e);
        }
    }

    status = PENDING; // 成功之后的回调
    value = undefined; // 成功之后的值
    reason = undefined; // 失败的原因
    successCallback = []; // 成功回调
    failCallback = []; // 失败回调

    resolve = value => {
        // 如果状态不是等待，阻止程序向下执行
        if (this.status !== PENDING) return;
        // 将状态更改火成功
        this.status = FULFILLED;
        // 保存成功之后的值
        this.value = value;
        while(this.successCallback.length) this.successCallback.shift()();
    }

    reject = reason => {
        // 如果状态不是等待，阻止程序向下执行
        if (this.status !== PENDING) return;
        // 将程序状态放改为失败
        this.status = REJECTED;
        // 保存失败后的原因
        this.reason = reason;
        while(this.failCallback.length) this.failCallback.shift()()
    }

    then (successCallback, failCallback) {
        // 参数可选
        successCallback = typeof successCallback == 'function' ? successCallback : value => value;
        failCallback = typeof failCallback == 'function' ? failCallback : reason => { throw reason }
        let promise2 = new MyPromise((resolve, reject) => {
            // 判断状态
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                })
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                })
            } else {
                // 将成功回调和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e);
                        }
                    })
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e);
                        }
                    })
                })
            }
        })
        return promise2;
    }

    finally (callback) {
        return this.then(value => {
            return MyPromise.resolve(callbakc()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }

    catch (failCallback) {
        return this.then(undefined, failCallback);
    }

    static all (array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index >= array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                if (current instanceof Mypromise) {
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, array[i])
                }
            }
        })
    }

    static resolve (value) {
        if (value instanceof MyPromsie) return value;
        return new MyPromise(resolve => resolve(value));
    }
}

function resolvePromise (promise2, x, resolve, reject) {
    // 判断 x 和 promise2 是否同一用promise实例，是则抛出错误
    // 判断 x 的值是普通值还是promise对象
    // 如果是普通值 直接调用resolve
    // 如果是promise对象 查看promise对象返回的结果
    // 再根据promise对象返回的结果 决定调用resolve还是调用reject
    if (promise2 === x) {
        return reject(new TypeError('chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject);
    } else {
        resolve(x)
    }
}



// const mp = new MyPromise(() => {
//     console.log('mp')
// })

// console.log(mp.hasOwnProperty('status'))
// console.log(mp.hasOwnProperty('resolve'))


function p1 () {
    return new MyPromise(function (resolve, reject) {
      setTimeout(function () {
        // resolve('p1')
        reject('err')
      }, 2000)
    })
  }
  function p2 () {
    return new MyPromise(function (resolve, reject) {
      reject('失败')
      // resolve('成功');  
    })
  }

  p1().then(res => {
      console.log(res)
  }, err => {
      console.log(err)
  })
  
  p2()
    .then(value => console.log(value))
    .catch(reason => console.log(reason))